import React, { Component } from 'react'
import ValidFolderName from 'graphql/dataset/validFolderName.graphql'
import NewFolder from 'graphql/dataset/newFolder.graphql'
import { ValidType } from 'components/validForm'
import {
  Form as FormTable, Section as TableSection, Input, Submit,
} from 'components/tableForm'

const getVariables = values => ({
  name: values.name.value,
})

export default class newDataset extends Component {
  componentDidMount = () => {}

  render() {
    const {
      activeDatasetId, activeDataset, match, orgName,
    } = this.props
    let { path } = match.params
    path = path || ''
    console.log('&&&&&&&&&*************', match)
    const folderNameRule = [
      {
        type: ValidType.REGULAR,
        value: /^[\s\S]*.*[^\s][\s\S]*$/,
        errorMessage: '文件夹名称不能为空',
      },
      {
        type: ValidType.REGULAR,
        value: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
        errorMessage: '数据集名称由中文、英文数字包括下划线',
      },
      {
        type: ValidType.REMOTE,
        value: {
          query: ValidFolderName,
          params: { datasetId: activeDatasetId, path },
        },
        errorMessage: '名字重复',
        getResult: re => re.dataset_item.length === 0,
      },
    ]
    return (
      <FormTable>
        <TableSection header="新建文件夹">
          <Input
            name="name"
            header="文件夹"
            description="文件夹名称由字符组成 ，可包含 字母、数字、下划线。"
            rules={folderNameRule}
          />
        </TableSection>
        <Submit
          submit={{
            text: '创建',
            variables: { datasetId: activeDatasetId, path },
            getVariables,
            mutation: NewFolder,
            success: (data) => {
              if (data && data.insert_dataset_item && data.insert_dataset_item.returning) {
                const { name } = data.insert_dataset_item.returning[0]
                return `/dataset/${orgName}/${activeDataset}/data/${path}/${name}`
              }
              return '/'
            },
          }}
          cancle={{ text: '取消', url: `/dataset/${orgName}/${activeDataset}/data/${path}` }}
        />
      </FormTable>
    )
  }
}
